﻿using Colorful.Database;
using System;
using System.Collections.Generic;
using System.Text;
using MongoDB.Driver;

namespace Colorful.CMS.Core
{
    public class SubmitService : IDisposable
    {
        private DbContext _db;
        private string _key;
        private int _limitCount;

        /// <summary>
        /// 限制次数（超过该参数则显示验证码)
        /// </summary>
        public int LimitCount
        {
            get
            {
                return _limitCount;
            }
        }
        /// <summary>
        /// SubmitService
        /// </summary>
        /// <param name="type">验证码类型</param>
        /// <param name="limitCount">限制次数（超过该参数则显示验证码)</param>
        public SubmitService(string type, int limitCount = 5)
            : this(type, CMSDbHelper.GetDb(), limitCount)
        {
        }
        public SubmitService(string type, DbContext db, int limitCount)
        {
            _db = db;
            _limitCount = limitCount;
            _key = $"{type}-{System.Web.HttpContext.Current.GetTrackingId()}";
        }

        /// <summary>
        /// 是否需要验证验证码
        /// </summary>
        /// <returns></returns>
        public bool IsValidate()
        {
            var result = _db.Counters.FirstOrDefault(a => a.Id == _key);
            if (result == null) return false;
            return result.Count >= _limitCount;
        }
        /// <summary>
        /// 设置计数器
        /// </summary>
        /// <param name="expireMinutes">超时时间（分钟）</param>
        /// <returns></returns>
        public long SetCounter(int expireMinutes = 60)
        {
            var counter = _db.Counters.FirstOrDefault(a => a.Id == _key);
            if (counter == null)
                counter = new Models.Counter() { Id = _key, Count = 0, LastModify = DateTime.Now };
            if (DateTime.Now > counter.LastModify.AddMinutes(expireMinutes))
                counter.Count = 0;
            else
                counter.Count++;
            _db.Counters.Update1(a => a.Id == _key, b => b.Count, counter.Count, b => b.LastModify, DateTime.Now, true);
            return counter.Count;
        }
        /// <summary>
        /// 是否显示验证码
        /// </summary>
        /// <param name="expireMinutes">超时时间（分钟）</param>
        /// <returns></returns>
        public bool ShowCaptcha(int expireMinutes = 60)
        {
            return this.SetCounter(expireMinutes) >= _limitCount;
        }
        /// <summary>
        /// 重置计数器
        /// </summary>
        public void Reset()
        {
            _db.Counters.Delete(a => a.Id == _key);
        }

        public void Dispose()
        {
            _db.Dispose();
            _db = null;
        }
    }
}
